package com.dundun.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dundun.common.utils.Ajax;
import com.dundun.domain.Browse;
import com.dundun.domain.Internship;
import com.dundun.domain.User;
import com.dundun.service.BrowseService;
import com.dundun.service.InternshipService;
import com.dundun.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Api(tags = "浏览相关接口")
@RequestMapping("/")
@RestController
public class BrowseController {

    @Resource
    private UserService userService;

    @Resource
    private BrowseService browseService;

    @Resource
    private InternshipService internshipService;

    @ApiOperation(value = "记录用户的访问历史记录")
    @PostMapping("/PutHistoryRecord")
    public Ajax putHistoryRecord(int internshipId, int userId) {
        if (internshipId < 0 || userId < 0) {
            return Ajax.error("不存在该职位或用户");
        }
        Internship internship = internshipService.getById(internshipId);
        User user = userService.getById(userId);
        if (internship == null) {
            return Ajax.error("不存在该职位");
        }
        if (user == null) {
            return Ajax.error("请先登录");
        }
        Browse browse = new Browse();
        browse.setUserId(user.getUserId());
        browse.setInternshipId(internship.getInternshipId());
        browse.setBrowseTime(new Date());
        internship.setBrowsedNum(internship.getBrowsedNum()+1);
        browseService.save(browse);
        internshipService.updateById(internship);
        return Ajax.success();
    }

    @ApiOperation(value = "获取用户的访问历史记录岗位列表")
    @GetMapping("/GetMyRecently")
    public Ajax getMyRecently(int userId) {
        if (userId < 0) {
            return Ajax.error("不存在该用户");
        }
        User user = userService.getById(userId);
        if (user == null) {
            return Ajax.error("请先登录");
        }
        List<Browse> browseList = browseService.list(new QueryWrapper<Browse>()
                .eq("user_id", userId).orderByDesc("browse_time"));
        ArrayList<Internship> internshipList = new ArrayList<>();
        browseList.forEach(b -> internshipList.add(internshipService.getById(b.getInternshipId())));
        return Ajax.success().put("data", internshipList);
    }

    @ApiOperation(value = "分页获取用户的访问历史记录岗位列表")
    @GetMapping("/GetMyRecentlyByPage")
    public Ajax GetMyRecentlyByPage(int userId) {
        return Ajax.success().put("data", "the return data...");
    }
}
